package com.ldzy.controller;

import com.ldzy.pojo.User;
import com.ldzy.service.IUserService;
import com.ldzy.utilts.RespUtil;
import com.ldzy.utilts.Response;
import com.ldzy.utilts.ResponseCode;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource IUserService iUserService;


    @PostMapping("/login")
    public RespUtil login(@RequestBody User user,HttpServletRequest request){
        System.out.println(user.toString());
        try {
            User user1= iUserService.login(user);
            if (user1!=null)
            {
                request.getSession().setAttribute("USER_SESSION",user1);
                return  RespUtil.success("登陆成功");
            }
            return  RespUtil.error("登录失败,密码错误！");
        }catch (Exception e){
            e.printStackTrace();
            request.setAttribute("msg","系统错误");
            return  RespUtil.error("登录失败，系统错误");
        }
    }
    @PostMapping("/logout")
    public  RespUtil logout(HttpServletRequest request){
        System.out.println("1111111111111111");
        System.out.println(request.getRequestURI());
        try {
            HttpSession session = request.getSession();
            session.invalidate();
            return  RespUtil.success("注销成功");
        }catch (Exception e){
            e.printStackTrace();
//            request.setAttribute("msg","系统错误");
            return  RespUtil.error("注销失败，系统错误");
        }
    }
    @PostMapping("/register")
    public  RespUtil register(@RequestBody User user){
        System.out.println("开始注册！");
        user.setStatus("0");
        if (iUserService.save(user)){
            return RespUtil.success("注册成功！");
        }
        return RespUtil.error("注册失败！");
    }
    @PostMapping("/Administrators")
    public RespUtil Administrators(@RequestBody User user,HttpServletRequest request){
        System.out.println(user.toString());
        try {
            User user1= iUserService.Administrators(user);
            if (user1!=null)
            {
                request.getSession().setAttribute("USER_SESSION",user1);
                return  RespUtil.success("欢迎回来，管理员");
            }
            return  RespUtil.error("登录失败,密码错误！");
        }catch (Exception e){
            e.printStackTrace();
            request.setAttribute("msg","系统错误");
            return  RespUtil.error("登录失败，系统错误");
        }
    }
}
